package com.begamer.card.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.begamer.card.cache.Cache;
import com.begamer.card.common.Constant;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.common.util.binRead.ChannelData;
import com.begamer.card.common.util.binRead.ServersData;
import com.begamer.card.json.GiftJson;
import com.begamer.card.json.ServerJson;
import com.begamer.card.json.ServerListJson;
import com.begamer.card.json.VersionJson;
import com.begamer.card.json.VersionResultJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.log.MemLogger;

public class GiftKeyController extends AbstractMultiActionController
{
	private static Logger memlogger=MemLogger.logger;
	private static final Logger errorlogger = ErrorLogger.logger;
	
	//玩家领取一个礼包
	public ModelAndView playerGetOneGift(HttpServletRequest request, HttpServletResponse response)
	{
		String ip=request.getRemoteAddr();
		if(!ServersData.isValidIp(ip))
		{
			return null;
		}
		int serverId = StringUtil.getInt(request.getParameter("serverId"));
		int playerId = StringUtil.getInt(request.getParameter("playerId"));
		String code = request.getParameter("code");
		String password = request.getParameter("password");
		if (!password.equals(Constant.GiftPassword))
		{
			memlogger.info(ip+"没有通信密码");
			return null;
		}
		if(serverId != 0 && playerId != 0 && null!=code && !"".equals(code))
		{
			GiftJson gj = Cache.getInstance().playerGetOneGift(serverId, playerId, code);
			request.setAttribute("result", JSON.toJSONString(gj));
			return new ModelAndView("result.vm");
		}
		return null;
	}
	
	/**
	 * 服务器列表和公告 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView serverList(HttpServletRequest request,HttpServletResponse response){
		try{
			boolean cheatSuccess=false;
			String cheatKey=RequestUtil.readParams(request);
			List<String> list = new ArrayList<String>();
			
//			//安卓和ios越狱版本、台湾版本
			if("".equals(cheatKey)||null==cheatKey){
				for (ServersData sd : ServersData.getDatas()){
					if(sd.type<=2){
						String s = sd.id + "-" + sd.name + "-" + sd.ip + "-" + sd.port+ "-" + sd.type + "-" + sd.state;
						list.add(s);
					}
				}
			}else{
				if("879243".equals(cheatKey)){
					cheatSuccess=true;
				}
				for (ServersData sd : ServersData.getDatas()){
					String s="";
					if(cheatSuccess){
						if(sd.type>2){
							s = sd.id + "-" + sd.name + "-" + sd.ip + "-" + sd.port+ "-" + sd.type + "-" + 0;
							memlogger.info("作弊成功:"+request.getRemoteAddr());
							list.add(s);
						}
					}else{
						if(sd.type<=2){
							s = sd.id + "-" + sd.name + "-" + sd.ip + "-" + sd.port+ "-" + sd.type + "-" + sd.state;
							list.add(s);
						}
					}
				}
			}
			//appstore
//			if("".equals(cheatKey)||null==cheatKey||!cheatKey.contains(",")){
//				memlogger.info("msg:" + "发送的格式错误!");
//			}else{
//				if(!"".equals(cheatKey)&&null!=cheatKey&&cheatKey.contains(",")){
//					String[] ss = cheatKey.split(",");
//					String s1 = ss[0];
//					String s2 = ss[1];
//					String[] version = s2.split("\\.");
//					int cVersion = 100*(Integer.valueOf(version[0]))+10*(Integer.valueOf(version[1]))+1*(Integer.valueOf(version[2]));
//					String[] version2 = Cache.getInstance().getVersion().split("\\.");
//					int sVersion = 100*(Integer.valueOf(version2[0]))+10*(Integer.valueOf(version2[1]))+1*(Integer.valueOf(version2[2]));
//					if(cVersion>sVersion){
//						if("879243".equals(s1)){
//							cheatSuccess=true;
//						}
//						for (ServersData sd : ServersData.getDatas()){
//							if(null!=sd&&sd.type>2){
//								String s="";
//								if(cheatSuccess){
//									s = sd.id + "-" + sd.name + "-" + sd.ip + "-" + sd.port+ "-" + sd.type + "-" + 0;
//									memlogger.info("作弊成功:"+request.getRemoteAddr());
//								}else{
//									s = sd.id + "-" + sd.name + "-" + sd.ip + "-" + sd.port+ "-" + sd.type + "-" + sd.state;
//								}
//								list.add(s);
//							}
//						}
//					}else{
//						if("879243".equals(s1)){
//							cheatSuccess=true;
//						}
//						for (ServersData sd : ServersData.getDatas()){
//							if(null!=sd&&sd.type<=2){
//								String s="";
//								if(cheatSuccess){
//									s = sd.id + "-" + sd.name + "-" + sd.ip + "-" + sd.port+ "-" + sd.type + "-" + 0;
//									memlogger.info("作弊成功:"+request.getRemoteAddr());
//								}else{
//									s = sd.id + "-" + sd.name + "-" + sd.ip + "-" + sd.port+ "-" + sd.type + "-" + sd.state;
//									//memlogger.info("s:"+s);
//								}
//								list.add(s);
//							}
//						}
//					}
//				}
//			}
			ServerListJson slj = new ServerListJson();
			slj.list = list;
			slj.announce = Cache.announce;
			String msg = JSON.toJSONString(slj);
			logger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}catch (Exception e){
			errorlogger.error(this.getClass().getName() + "->"+ Thread.currentThread().getStackTrace()[1].getMethodName()+ "():", e);
		}
		return new ModelAndView("/user/result.vm");
	}

	/**
	 * 游戏版本
	 * lt@2014-6-9 下午02:17:27
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView serverVersion(HttpServletRequest request,HttpServletResponse response)
	{
		try
		{
			JSONObject jsonObject=RequestUtil.getJsonObject(request);
			VersionJson vj=JSONObject.toJavaObject(jsonObject, VersionJson.class);
			VersionResultJson vrj=new VersionResultJson();
			if(vj!=null)
			{
				memlogger.info("客户端版本号:" + vj.versionId+",channelId:"+vj.channelId);
				String serverVersion=Cache.getInstance().getVersion();
				//安卓和ios越狱版本
		
				String[] version = vj.versionId.split("\\.");
				int cVersion = 100*(Integer.valueOf(version[0]))+10*(Integer.valueOf(version[1]))+1*(Integer.valueOf(version[2]));
				String[] version2 = serverVersion.split("\\.");
				int sVersion = 100*(Integer.valueOf(version2[0]))+10*(Integer.valueOf(version2[1]))+1*(Integer.valueOf(version2[2]));
				//logger.info("cVersion:"+cVersion+",sVersion:"+sVersion);
				if(cVersion==sVersion){
					vrj.mark=1;
					vrj.binPath=Cache.getInstance().getDownloadPath()+"/"+vj.versionId+"/bins_2/";
					//logger.info("vrj.binPath:"+vrj.binPath);
				}else if(cVersion>sVersion){
					vrj.mark=1;
					vrj.binPath="http://localhost/down/"+vj.versionId+"/bins/";
				}else{
					vrj.mark = 0;
					String channelId = vj.channelId;
					String platform = vj.platform;
					memlogger.info("channelId:" + channelId + ",platform:"+ platform);
					ChannelData cd = ChannelData.getChannelData(channelId);
					if (cd != null && cd.packagePath != null&& !"".equals(cd.packagePath)) {
						vrj.binPath = Cache.getInstance().getDownloadPath()+ "/" + serverVersion + "/packages/"	+ channelId + "/" + cd.packagePath;
					}
					if (vrj.binPath == null || "".equals(vrj.binPath)) {
						vrj.mark = 0;
						vrj.binPath = Cache.announce;
					}
				}
				
				//台湾版本
//				if(serverVersion.equals(vj.versionId)){
//					vrj.mark=1;
//					vrj.binPath=Cache.getInstance().getDownloadPath()+"/tw/"+serverVersion+"/bins_11/";
//				}else{
//					vrj.mark=0;
//					String channelId=vj.channelId;
//					String platform=vj.platform;
//					memlogger.info("channelId:" + channelId+",platform:"+platform);
//					ChannelData cd=ChannelData.getChannelData(channelId);
//					if(cd!=null && cd.packagePath!=null && !"".equals(cd.packagePath)){
//						vrj.binPath=Cache.getInstance().getDownloadPath()+"/tw/"+serverVersion+"/packages/"+channelId+"/"+cd.packagePath;
//					}
//					if(vrj.binPath==null || "".equals(vrj.binPath)){
//						vrj.mark=0;
//						vrj.binPath=Cache.announce;
//					}
//				}
				
				
				//appstore官方
//				String[] version = vj.versionId.split("\\.");
//				int cVersion = 100*(Integer.valueOf(version[0]))+10*(Integer.valueOf(version[1]))+1*(Integer.valueOf(version[2]));
//				String[] version2 = serverVersion.split("\\.");
//				int sVersion = 100*(Integer.valueOf(version2[0]))+10*(Integer.valueOf(version2[1]))+1*(Integer.valueOf(version2[2]));
//				if(cVersion>=sVersion){
//					vrj.mark=1;
//					vrj.binPath=Cache.getInstance().getDownloadPath()+"/app/"+vj.versionId+"/bins_11/";
//				}else{
//					vrj.mark = 0;
//					String channelId = vj.channelId;
//					String platform = vj.platform;
//					memlogger.info("channelId:" + channelId + ",platform:"+ platform);
//					ChannelData cd = ChannelData.getChannelData(channelId);
//					if (cd != null && cd.packagePath != null&& !"".equals(cd.packagePath)) {
//						vrj.binPath = Cache.getInstance().getDownloadPath()+ "/app/" + serverVersion + "/packages/"	+ channelId + "/" + cd.packagePath;
//					}
//					if (vrj.binPath == null || "".equals(vrj.binPath)) {
//						vrj.mark = 0;
//						vrj.binPath = Cache.announce;
//					}
//				}
			}
			String msg = JSON.toJSONString(vrj);
			//memlogger.info("msg:" + msg);
			RequestUtil.setResponseMsg(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"+ Thread.currentThread().getStackTrace()[1].getMethodName()+ "():", e);
		}
		return new ModelAndView("/user/result.vm");
	}
	
	public ModelAndView getWebIp(HttpServletRequest request,HttpServletResponse response)
	{
		String ip=null;
		int serverId=StringUtil.getInt(request.getParameter("serverId"));
		List<ServersData> sds=ServersData.getDatas();
		for(ServersData sd:sds)
		{
			if(sd.id==serverId)
			{
				ip=sd.ip+":"+sd.port;
				break;
			}
		}
		request.setAttribute("result", ip);
		return new ModelAndView("/user/result.vm");
	}
	
	public ModelAndView getServers(HttpServletRequest request,HttpServletResponse response)
	{
		List<ServerJson> list=new ArrayList<ServerJson>();
		List<ServersData> sds=ServersData.getDatas();
		for(ServersData sd:sds)
		{
			ServerJson sj=new ServerJson();
			sj.server=sd.id+"";//服务器Id
			sj.name=sd.name;//服务器名字
			sj.ip=sd.ip;
			sj.port=sd.port;
			sj.state=(sd.state==1)?"off":"on";//状态:on\off
			list.add(sj);
		}
		String json=JSON.toJSONString(list);
		System.out.println(json);
		request.setAttribute("result", json);
		return new ModelAndView("/user/result.vm");
	}
	
}
